
import React from 'react';
import { Message, Sender } from '../types';
import { BotIcon, UserIcon } from './Icons';
import CodeBlock from './CodeBlock';

interface ChatMessageProps {
  message: Message;
  isStreaming: boolean;
}

// A simple parser to separate text and code blocks
const parseMessageContent = (text: string) => {
  if (!text) return [];
  const parts: { type: 'text' | 'code'; content: string; language?: string }[] = [];
  const codeBlockRegex = /```(\w+)?\n([\s\S]+?)\n```/g;
  let lastIndex = 0;
  let match;

  while ((match = codeBlockRegex.exec(text)) !== null) {
    // Add text part before the code block
    if (match.index > lastIndex) {
      parts.push({ type: 'text', content: text.substring(lastIndex, match.index) });
    }
    // Add code block part
    parts.push({ type: 'code', language: match[1] || 'plaintext', content: match[2].trim() });
    lastIndex = codeBlockRegex.lastIndex;
  }

  // Add any remaining text part
  if (lastIndex < text.length) {
    parts.push({ type: 'text', content: text.substring(lastIndex) });
  }

  return parts;
};


const ChatMessage: React.FC<ChatMessageProps> = ({ message, isStreaming }) => {
  const isUser = message.sender === Sender.User;
  const parsedContent = parseMessageContent(message.text);

  const containerClasses = isUser ? 'justify-end' : 'justify-start';
  const bubbleClasses = isUser
    ? 'bg-cyan-900/50 text-slate-200'
    : 'bg-slate-700 text-slate-300';

  return (
    <div className={`flex items-start gap-3 ${containerClasses}`}>
      {!isUser && <BotIcon className="w-7 h-7 flex-shrink-0 mt-1" isThinking={isStreaming} />}
      <div className={`max-w-4xl w-fit rounded-lg px-4 py-3 ${bubbleClasses}`}>
        {parsedContent.length > 0 ? (
          parsedContent.map((part, index) =>
            part.type === 'code' ? (
              <CodeBlock key={index} language={part.language!} code={part.content} />
            ) : (
              <p key={index} className="whitespace-pre-wrap leading-relaxed">{part.content}</p>
            )
          )
        ) : (
          isStreaming && (
            <div className="flex items-center space-x-2">
                <span className="w-2 h-2 bg-slate-200/50 rounded-full animate-pulse"></span>
                <span className="w-2 h-2 bg-slate-200/50 rounded-full animate-pulse delay-75"></span>
                <span className="w-2 h-2 bg-slate-200/50 rounded-full animate-pulse delay-150"></span>
            </div>
          )
        )}
      </div>
       {isUser && <UserIcon className="w-7 h-7 flex-shrink-0 text-slate-400 mt-1" />}
    </div>
  );
};

export default ChatMessage;
